package com.sxj.web.util;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;

/**
 * @author 石小俊
 * @date 2024年03月08日 20:41
 */
public class CookieUtil {

    public static void addCookie(String name, String value, HttpServletResponse response){
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void addCookie(String name, String value, int maxAge, HttpServletResponse response){
        try {
            Cookie cookie = new Cookie(name, URLEncoder.encode(value,"UTF-8"));
            cookie.setMaxAge(maxAge);
            response.addCookie(cookie);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
    }

    public static void deleteCookie(String name,HttpServletResponse response){
        addCookie(name,"",0,response);
    }

    public static void modifyCookie(String name,String value,HttpServletResponse response){
        addCookie(name,value,response);
    }

    public static void modifyCookie(String name,String value,int maxAge,HttpServletResponse response){
        addCookie(name,value,maxAge,response);
    }

    public static String findByName(String name, HttpServletRequest request){
        Cookie[] cookies = request.getCookies();
        try {
            if(cookies != null){
                for(Cookie cookie : cookies){
                    if(cookie.getName().equals(name)){
                        return URLDecoder.decode(cookie.getValue(),"UTF-8");
                    }
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

}
